﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HandWriter.Controls
{
	public class ToolPanel : Panel
	{
		private int _mx;
		private int _my;
		private int _ol;
		private int _ot;
		private bool _track;

		private System.Windows.Forms.Button closeButton;

		[Category("Design")] 
		public String Caption { get; set; }

		[Category("Design")]
		public Image Image { get; set; }

		[Category("Behavior")]
		public event EventHandler OnCloseButtonClick;

		public ToolPanel()
		{
			Paint += panelPaint;
			Click += panelClick;
			MouseDown += panelMouseDown;
			MouseMove += panelMouseMove;
			MouseUp += panelMouseUp;

			this.closeButton = new System.Windows.Forms.Button();
			this.closeButton.Location = new System.Drawing.Point(Width - 16, 4);
			this.closeButton.Name = "closeButton";
			this.closeButton.Size = new System.Drawing.Size(12, 12);
			this.closeButton.TabIndex = 5;
			this.closeButton.Text = "x";
			this.closeButton.UseVisualStyleBackColor = true;
			this.closeButton.Click += closeClick;
			Controls.Add(closeButton);
			
		}

		private void closeClick(object sender, EventArgs e)
		{
			Visible = false;
			if (OnCloseButtonClick != null)
			{
				OnCloseButtonClick(this, e);
			}
		}

		private void panelPaint(object sender, PaintEventArgs e)
		{
			if (Image != null)
			{
				e.Graphics.DrawImage(Image, new PointF(2, 2));
			}
			e.Graphics.FillRectangle(SystemBrushes.ActiveCaption, 20, 0, Width - 10, 20);
			e.Graphics.DrawString(Caption, Font, SystemBrushes.ActiveCaptionText, 24, 4);
		}

		private void panelClick(object sender, EventArgs e)
		{
			
		}

		private void SetInitMouseDrag()
		{
			_ol = Left;
			_ot = Top;
			_mx = Cursor.Position.X;
			_my = Cursor.Position.Y;
		}

		private void panelMouseDown(object sender, MouseEventArgs e)
		{
			SetInitMouseDrag();
			_track = true;
		}

		private void panelMouseMove(object sender, MouseEventArgs e)
		{
			if (_track)
			{
				Left = _ol + Cursor.Position.X - _mx;
				Top = _ot + Cursor.Position.Y - _my;

				if (Left < 0)
				{
					Left = 0;
					SetInitMouseDrag();
				}

				if (Top < 0)
				{
					Top = 0;
					SetInitMouseDrag();
				}

				if (Right > Parent.ClientSize.Width)
				{
					Left = Parent.ClientSize.Width - Width;
					SetInitMouseDrag();
				}

				if (Bottom > Parent.ClientSize.Height)
				{
					Top = Parent.ClientSize.Height - Height;
					SetInitMouseDrag();
				}
			}
		}

		private void panelMouseUp(object sender, MouseEventArgs e)
		{
			_track = false;
		}
	}
}
